package com.xyt.imei.core.api;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.luminary.common.framework.core.auth.ValidateToken;
import com.luminary.common.framework.core.model.Pagination;
import com.luminary.common.framework.core.model.SimpleResponse;
import com.luminary.component.util.common.BeanMapUtils;
import com.xyt.imei.core.meta.PageConstants;
import com.xyt.imei.core.meta.RoleEnum;
import com.xyt.imei.core.model.converter.TraceConverter;
import com.xyt.imei.core.model.dto.TraceQueryDTO;
import com.xyt.imei.core.model.po.Trace;
import com.xyt.imei.core.model.po.User;
import com.xyt.imei.core.model.vo.TraceVO;
import com.xyt.imei.core.service.TraceService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("trace")
public class TraceApi {
	
	@Autowired
	private TraceConverter traceConverter;
	
	@Autowired
	private TraceService traceService;
	
	@ValidateToken(roles = {RoleEnum.ADMIN_VALUE + "", RoleEnum.CMCC_VALUE + "",})
	@GetMapping("/page")
	public SimpleResponse query(
			@Valid TraceQueryDTO traceQueryDTO,
			@PageableDefault(page=PageConstants.DEFAULT_PAGE_NO,size=PageConstants.DEFAULT_PAGE_SIZE)
			@SortDefault.SortDefaults({
				@SortDefault(sort = "create_date", direction = Direction.DESC)
			}) Pageable pageable,
			HttpServletResponse response
		) throws Exception {
		
		log.info("traceQueryDTO:" + traceQueryDTO.toString() + ",pageable:" + pageable.toString());
		
		Pagination<Trace> pagination = new Pagination<Trace>(pageable);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params = BeanMapUtils.beanToMap(traceQueryDTO);
		pagination.setParams(params, pageable);
		
		pagination = traceService.findByPage(pagination);
		pagination.getResults();
		
		Pagination<TraceVO> page = new Pagination<TraceVO>(pageable);
		BeanUtils.copyProperties(pagination, page);
		
		page.setResults(traceConverter.po2vo(pagination.getResults()));
		
		return SimpleResponse.success(page, response);
		
	}
	
}
